package com.peycard.util;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;

import com.peycard.service.BaseTransaction;

public class Utils {

	public static String terminalID() throws UnknownHostException {
		InetAddress ip = InetAddress.getLocalHost();
		String string = ip.getHostAddress();
		return "POR" + string.substring(string.length() - 2) + "00000000000";
	}

	public static Map<String, String> getKeyValues(String metadata, String data) {
		Map<String, String> mapa = new HashMap<String, String>();
		String[] splitedMetadata = metadata.split("\\|");
		String[] splitedData = data.split("\\|");
		for (int i = 0; i < splitedMetadata.length; i++) {
			mapa.put(splitedMetadata[i], splitedData[i]);
		}
		return mapa;
	}

	public static List<String> getListValues(String mapValue) {
		List<String> stringList = new ArrayList<String>();
		StringBuilder str = new StringBuilder(mapValue);
		str.delete(0, 2);
		str.delete(str.length() - 2, str.length());
		String string = str.toString();
		if (string.contains("], [")) {
			return (Arrays.asList(string.split("\\], \\[")));
		} else {
			stringList.add(string);
			return stringList;
		}
	}

	public static List<String> convertList(String item) {
		StringBuilder str = new StringBuilder(item);
		String string = str.toString();
		return (Arrays.asList(string.split(", ")));
	}

	public static String buildStringData(List<Object> data) {
		StringBuilder strBuilder = new StringBuilder();
		for (int i = 0; i < data.size(); i++) {
			strBuilder.append(data.get(i));
			strBuilder.append("|");
		}
		strBuilder.deleteCharAt(strBuilder.length() - 1);
		return strBuilder.toString();
	}

	public static final Map<String, String> baseMap(BaseTransaction base) {
		String keys = base.getField126_resp_lllvar_metadata();
		String values = base.getField127_resp_lllvar_data();
		Map<String, String> map = Utils.getKeyValues(keys, values);
		return map;
	}

	public static final String getMessage(BaseTransaction base) {
		Map<String, String> map = baseMap(base);
		return map.get(Constantes.DESCRIPTION_KEY);
	}

	public static final String encryptPassword(String password) {
		String encrypted = DigestUtils.sha256Hex(password);
		return encrypted;
	}
}
